const createElement = (tag, attrs = {}) => {
  const el = document.createElement(tag);
  Object.entries(attrs).forEach(([key, value]) => {
    el.setAttribute(key, value);
  });
  return el;
};

// 右键菜单处理
const contextMenu = document.getElementById('contextMenu');

// 关闭菜单
document.addEventListener('click', e => {
  if (!contextMenu.contains(e.target)) {
    contextMenu.style.display = 'none';
  }
});


let savedRange = null

// 创建注释标记
const createAnnotationMarker = (textData) => {
  console.log(`textData: ${textData}`);
  const marker = createElement('span', {
    'class': 'annotation-marker',
  });
  marker.textContent = '※'
  marker.setAttribute('annotation', textData)
  marker.addEventListener('click', (e) => {
    const element = e.target
    console.log(`annotation: ${element.getAttribute('annotation')}`);
    window.manager.showAnnotation(element.getAttribute('annotation'))
  })
  return marker;
};


// 添加注释
document.getElementById('addAnnotation').addEventListener('click', () => {
  console.log(`addAnnotation click`);
  window.manager.addAnnotation()
});


function createAnnotationElement(annotation) {
  if (annotation && savedRange) {
    const selection = window.getSelection()
    selection.removeAllRanges()
    selection.addRange(savedRange)

    // 安全插入节点
    const marker = createAnnotationMarker(annotation);
    savedRange.insertNode(marker);
    savedRange.collapse(false);
    savedRange = null
  }
  contextMenu.style.display = 'none';
}

const customPopup = document.getElementById('contextMenu')
let longPressTimer


// 监听触摸开始事件
editor.addEventListener('touchstart', (e) => {
  console.log('touchstart');
  const selection = window.getSelection()
  savedRange = selection.getRangeAt(0).cloneRange()
  if (savedRange === null) {
    console.log('touchstart, savedRange is null');
  } else {
    console.log('touchstart, savedRange is not null');
  }

  // 设置定时器，500ms后触发长按
  longPressTimer = setTimeout(() => {
    showCustomPopup(e)
  }, 500);
})

// 监听触摸结束/取消事件
editor.addEventListener('touchend', clearTimer)
editor.addEventListener('touchcancel', clearTimer)

// 清除定时器
function clearTimer() {
  console.log('clearTimer')
  if (longPressTimer) {
    clearTimeout(longPressTimer)
    longPressTimer = null
  }
}

// 显示弹窗
function showCustomPopup(e) {
  console.log('showCustomPopup')
  // 获取触摸位置
  const touch = e.touches[0] || e.changedTouches[0]
  const x = touch.clientX
  const y = touch.clientY

  // 显示弹窗并定位
  customPopup.style.display = 'block'
  customPopup.style.left = `${x}px`
  customPopup.style.top = `${y}px`

  e.preventDefault()
}
